package GlavFinans::Module::Core::Controller::Contact;

use utf8;
use Data::Dumper;
use Mojo::Base 'Mojolicious::Controller';

sub form {
	my $self = shift;
	
	$self->render('core/contact/form', notes => []);
}

sub create {
	my $self = shift;
	
	my $config = $self->stash('config');
	
	my $form = $self->req->params->to_hash;
	warn Dumper($form);
		
	# Validation Rule
	my $rule = [
		'email' => {
			message => 'Указан неверный e-mail адрес',
			require => 0
		} => ['email'],
		'phone' => {
			message => 'Указан неверный номер телефона',
			require => 0
		} => ['phone'],
		'sender' => {
			message => 'Укажите контактную информацию'
		} => ['not_blank'],
		'message' => {
			message => 'Введите сообщение для отправки'
		} => ['not_blank'],
		'code' => {
			message => 'Введены неверные символы'
		} => ['not_blank']
	];
	
	my $vc = $self->stash('validator');	
	my $result = $vc->validate($form, $rule);
	$form = $result->data;
	
	my $mp = scalar @{$result->{missing_params}};
	
	if ($mp || !$result->is_ok) {
		$self->stash(missing => 1) if $result->has_missing;
		$self->stash(messages => $result->messages_to_hash) if $result->has_invalid;
		$self->stash(form => $form);
		$self->render('core/contact/form');
		return;
	}

	my $msg = $self->app->db->resultset('Message')->new();
	
	$msg->ip($self->req->env('REMOTE_ADDR'));
	$msg->phone($form->{phone});
	$msg->email($form->{email});
	$msg->type('foreign');
	$msg->sender($form->{sender});
	$msg->message($form->{message});
	$msg->insert();
	
	$self->app->mail(
		to      => $config->email->{customercare},
		subject => 'Контакт с сайта',
		data    => $form->{message}
	);
		
   	$self->flash('success' => 1);
   	$self->redirect_to('/contact');   
}

sub sent {
	my $self = shift;
	$self->render('core/contact/sent');
}

1;
